<?php

namespace App\Controller\music;

use App\Controller\AbstractController;
use App\Model\Music;
use App\Utils\Music\Meting;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use function Hyperf\Config\config;

class IndexController extends AbstractController
{

    #[Inject]
    protected Music $music;
    public function index()
    {
        $netease_cookie = '';
        // 歌曲源
        $source = $this->request->post('source', 'netease');
        $API = new Meting($source);
        $API->format(true); // 启用格式化功能
        if($source == 'kugou' || $source == 'baidu') {
            define('NO_HTTPS', true);        // 酷狗和百度音乐源暂不支持 https
        } elseif(($source == 'netease') && $netease_cookie) {
            $API->cookie($netease_cookie);    // 解决网易云 Cookie 失效
        }
        $types = $this->request->post('types','playlist');
        $id = $this->request->post('id');  // 歌曲ID
        if($types){
            // 根据请求的 Api，执行相应操作
            switch($types)
            {
                case 'url':   // 获取歌曲链接
                    $data = $API->url($id);
                    //获取歌曲信息
//                    $get_data = $API->song($id);
//                    $get_data = json_decode($get_data,true);
//                    $name = array_column($get_data,'name')[0];
//                    //判断文件下是否存在
//                    $file_path=BASE_PATH."/public/music/{$name}.mp3";
//                    if (!file_exists($file_path)){
//                        if($data){
//                            $datas = json_decode($data,true);
//                            $url = $datas['url'];
//                            $this->response->download($url,$name);
//                        }
//                    }
                    break;
                case 'pic':   // 获取歌曲链接
                    $data = $API->pic($id);
                    break;
                case 'lyric':       // 获取歌词
                    $data = $API->lyric($id);
                    break;
                case 'download':    // 下载歌曲(弃用)
                    $fileurl = $this->request->post('url');  // 链接
                    return $this->response->download($fileurl);
                    break;
                case 'userlist':    // 获取用户歌单列表
                    $uid = $this->request->post('uid');  // 用户ID
                    $url= 'http://music.163.com/api/user/playlist/?offset=0&limit=1001&uid='.$uid;
                    $data = file_get_contents($url);
                    break;
                case 'playlist':    // 获取歌单中的歌曲
                    $data = $API->format(false)->playlist($id);
                    break;
                case 'search':  // 搜索歌曲
                    $s = $this->request->post('name');  // 歌名
                    $limit = $this->request->post('count', 20);  // 每页显示数量
                    $pages = $this->request->post('pages', 1);  // 页码
                    $data = $API->search($s, [
                        'page' => $pages,
                        'limit' => $limit
                    ]);
                    break;
                default:
                    return $this->render->render('music/index');
            }
            if($data){
                $data = json_decode($data,true);
            }
            $callback = $this->request->input('callback','callback');
            if (!is_scalar($data) && null !== $data) {
                $data = json_encode($data);
            }
            return $this->response->write("$callback($data)");
        }else{
            return $this->render->render('music/index');
        }
    }

    /**
     * 音乐下载
     * @return ResponseInterface
     */
    public function getDownloadSongs()
    {
        $netease_cookie = '';
        // 歌曲源
        $source = $this->request->post('source', 'netease');

        $API = new Meting($source);
        $API->format(true); // 启用格式化功能
        if($source == 'kugou' || $source == 'baidu') {
            define('NO_HTTPS', true);        // 酷狗和百度音乐源暂不支持 https
        } elseif(($source == 'netease') && $netease_cookie) {
            $API->cookie($netease_cookie);    // 解决网易云 Cookie 失效
        }
        $data_post = $this->request->all();
        //歌手
        $artist = $data_post['artist'];
        //歌曲名
        $music_name = $data_post['name'];
        //歌曲id
        $music_id = $data_post['id'];
        //专辑
        $album = $data_post['album'];
        //专辑图片
        $album_pic = $data_post['pic'];
        //歌曲链接
        $download_url = $data_post['url'];
        if (empty($download_url)){
            $data = $API->url($music_id);
            //获取歌曲信息
            $get_data = $API->song($music_id);
            $get_data = json_decode($get_data,true);
            $name = array_column($get_data,'name')[0];
            //判断文件下是否存在
            $file_path=BASE_PATH."/public/music/{$name}.mp3";
            if (!file_exists($file_path)){
                if($data){
                    $datas = json_decode($data,true);
                    $url = $datas['url'];
                    $this->response->download($url,$name);
                }
            }
            return $this->error("链接错误");
        }
        $exists = $this->music->where('music_id',$music_id)->exists();
        if ($exists){
            $local_url = $this->music->where('music_id',$music_id)->value('local_url');
            return $this->success(["local_url"=>$local_url],"获取成功");
        }else{
            $local_url="";
            //把视频保存在本地 local_url
            $music_save_local_open = config('setting.music_save_local_open') ?? 1;
            if ($music_save_local_open == 0) {
                $connect = file_get_contents($download_url);
                if (empty($connect)){
                    return $this->error("下载失败");
                }
                $path_music = BASE_PATH."/public/music/music";
                if (!file_exists($path_music)) {
                    mkdir($path_music, 0777, true);
                }
                $path_date = BASE_PATH."/public/music/music". date('Ymd');
                if (!file_exists($path_date)) {
                    mkdir($path_date, 0777, true);
                }
                $public_path_music = "music/music/" . date('Ymd') . '/' .$music_name . ".mp3";
                $path_url = BASE_PATH."/public/".$public_path_music;
                file_put_contents($path_url, $connect);
                $local_url = $public_path_music;
            }
            $data = [
                'download_url' => $download_url,
                'music_name' => $music_name,
                'music_id' => $music_id,
                'singer' => $artist,
                'album' => $album,
                'pic' => $album_pic,
                'local_url' => $local_url,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
            ];
            $this->music->insert($data);
            return $this->success(['local_url'=>$local_url],"获取成功");
        }

    }
}